import { Controller, Get, Post, Put, Del, Inject, Body, Param, Query } from '@midwayjs/decorator';
import { StudentService } from '../../service/firmware/student.service';
import { Validate } from '@midwayjs/validate';
// import { CreateStudentDTO, UpdateStudentDTO } from '../../dto/firmware/student.dto';
import { Log, BusinessType } from "@decorator/log.decorator";
import { resBuild } from '@utils/resBuild';
import { createMiddleware, Files } from '@midwayjs/core';
import { UploadMiddleware, UploadStreamFileInfo } from '@midwayjs/busboy';
import { StudentWristbandService } from '@service/firmware/student_wristband.service';
@Controller('/student')
export class StudentController {
  @Inject()
  studentService: StudentService;
  @Inject()
  studentWristbandService: StudentWristbandService;



  // 创建学生手环关联 分配手环
  @Post('/createStudentWristband')
  @Validate() // 触发 DTO 验证
  async createStudentWristband(@Body() body) {
    try {
      await this.studentWristbandService.createAssociation(body);
      return resBuild.success("创建成功！");
    } catch (error) {
      console.log(error)
      return resBuild.fail(error.message);
    }
  }

  // 删除学生手环关联（回收）
  @Del('/deleteStuWb/:id')
  async deleteStuWb(@Query() params) {
    const deleted = await this.studentWristbandService.deleteAssociation(params);
    if (!deleted) return resBuild.fail('删除失败，学生不存在');
    return resBuild.success("删除成功");
  }



  // 创建学生
  @Post('/create')
  @Validate() // 触发 DTO 验证
  async create(@Body() body) {
    try {
      await this.studentService.createStudent(body);
      return resBuild.success("创建成功！");
    } catch (error) {
      console.log(error)
      return resBuild.fail(error.message);
    }
  }

  // 获取所有学生
  @Get('/list')
  async list(@Query() query) {
    try {
      console.log('学生传参', query)
      const students = await this.studentService.getAllStudents(query);
      console.log('查询结果', students)
      return resBuild.data(students);
    } catch (e) {
      console.log(e)
    }

  }

  // 获取单个学生
  @Get('/:id')
  async getById(@Param('id') id: number) {
    const student = await this.studentService.getStudentById(id);
    if (!student) return resBuild.fail("学生不存在");
    return resBuild.data(student);
  }

  // 更新学生信息
  @Put('/update/:id')
  @Validate() // 触发 DTO 验证
  async update(@Param('id') id: number, @Body() body) {
    try {
      const updatedStudent = await this.studentService.updateStudent(body);
      if (!updatedStudent) return resBuild.fail("更新失败，学生不存在");
      return resBuild.success("修改成功！");
    } catch (error) {
      return resBuild.fail(error.message);
    }
  }

  // 批量删除选中的学生
  @Post('/delete/selected')
  async deleteSelected(@Body() body) {
    try {
      const deletedCount = await this.studentService.deleteSelectedStudents(body.ids);
      return resBuild.success(`成功删除${deletedCount}名学生`)
    } catch (err) {
      return resBuild.fail(err.message || "删除失败")
    }

  }


  // 根据 class_id 清空班级所有学生
  @Del('/delete/selectAll/:class_id')
  async deleteAllByClass(@Param('class_id') class_id: number) {
    try {
      const deletedCount = await this.studentService.deleteAllStudentsByClass(class_id);
      return resBuild.success(`成功删除${deletedCount}名学生`)
    } catch (err) {
      resBuild.fail(err.message || "删除失败")
    }
  }

  // 删除学生
  @Del('/delete/:id')
  async delete(@Param('id') id: number) {
    const deleted = await this.studentService.deleteStudent(id);
    if (!deleted) return resBuild.fail("删除失败，学生不存在")
    return resBuild.success("删除成功")
  }

  // 下载导入模板
  @Get('/importTemplate')
  async importTemplate() {
    console.log('222', 'importTemplate')
    return await this.studentService.importTemplate();
  }


  // 下载导入模板(无班级参数)
  @Get('/importTemplateClass')
  async importTemplateClass() {
    console.log('222', 'importTemplateClass')
    return await this.studentService.importTemplateClass();
  }


  // 导入模板(携带班级参数)
  @Log({ title: '学生管理', businessType: BusinessType.IMPORT })
  @Post('/importDataClass', {
    middleware: [
      createMiddleware(UploadMiddleware, { mode: 'stream' })  // 再处理文件上传
    ]
  })
  async importData(
    @Files() files: UploadStreamFileInfo,
    @Query('updateSupport') updateSupport: boolean,
    @Query('class_id') class_id: number
  ) {
    try {
      return await this.studentService.importDataClass({
        class_id,
        files,
        updateSupport
      });
    } catch (err) {
      console.log('err222', err)
      return resBuild.fail(err.message)
    }

  }
}
